//
//  GLPrebuiltLiveRealmTranslationMessageView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/31.
//

import UIKit
import SnapKit

class GLPrebuiltLiveRealmTranslationMessageView: UIView {
    
    private var messageList: [MessageModel] = [MessageModel]()
    var originalDataList:[ZegoInRoomMessage] = [ZegoInRoomMessage]()
    
    var lastFrame: CGRect?
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height), style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.insetsContentViewsToSafeArea = false
        }
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.register(ZegoUIKitMessageCell.self, forCellReuseIdentifier: "ZegoUIKitMessageCell")
        addSubview(tableView)
        return tableView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initRoomMessageView()
    }
    
    private func initRoomMessageView() {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        ZegoUIKit.shared.addEventHandler(self)
        getAllMessage()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override var frame: CGRect {
        didSet {
            if let lastFrame = lastFrame, frame.equalTo(lastFrame) {
                return
            }
            lastFrame = frame
            MessageModelBuilder.messageViewWidth = self.frame.size.width
            tableView.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
            getAllMessage()
        }
    }
    
    fileprivate func getAllMessage() {
        messageList.removeAll()
        originalDataList = ZegoUIKit.shared.getInRoomMessages()
        for message in ZegoUIKit.shared.getInRoomMessages() {
            if let msgDic = message.message?.toDictionary(), let seiModel = JsonUtil.modelFromDictionary(msgDic, IMRecvSeiModel.self) {
                let model = MessageModelBuilder.buildModel(with: message.user, message: seiModel.text)
                messageList.append(model)
            }
        }
        tableView.reloadData()
    }
    
}

extension GLPrebuiltLiveRealmTranslationMessageView: ZegoUIKitEventHandle {
    
    func onInRoomMessageReceived(_ messageList: [ZegoInRoomMessage]) {
        originalDataList.append(contentsOf: messageList)
        // 发的弹幕也走这里，但是格式不一样，弹幕不带 type = 1
        // 实时翻译走这里， 带有 text 和 type = 1
        
        var newMessageList = [MessageModel]()
        for message in messageList {
            // xLog("实时翻译消息 \(message.message ?? "nil")")
            if let msgDic = message.message?.toDictionary(), let seiModel = JsonUtil.modelFromDictionary(msgDic, IMRecvSeiModel.self) {
                let model = MessageModelBuilder.buildModel(with: message.user, message: seiModel.text)
                newMessageList.append(model)
            }
        }
        self.messageList.append(contentsOf: newMessageList)
        tableView.reloadData()
        scrollToBottom()
    }
    
    func onInRoomMessageSendingStateChanged(_ message: ZegoInRoomMessage) {
        getAllMessage()
        scrollToBottom()
    }
    
    /// 滚动到最下
    func scrollToBottom() {
        
        UIView.animate(withDuration: 0, delay: 1.0, options: .allowUserInteraction, animations: {
            
        }) { finished in
            
            if self.tableView.isTracking ||
                self.tableView.isDragging ||
                self.tableView.isDecelerating {
                return
            }
            
            let index = self.messageList.count - 1
            if index >= 0 {
                self.tableView.scrollToRow(at: IndexPath(row: index, section: 0), at: .bottom, animated: true)
            }
        }
    }
}

extension GLPrebuiltLiveRealmTranslationMessageView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        messageList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "ZegoUIKitMessageCell") as? ZegoUIKitMessageCell
        
        if cell == nil {
            cell = ZegoUIKitMessageCell.init(style: .default, reuseIdentifier: "ZegoUIKitMessageCell")
        }
        
        if indexPath.row < messageList.count {
            let index: Int = indexPath.row
            cell!.messageModel = messageList[index]
        }
        cell!.selectionStyle = .none
        cell!.backgroundColor = UIColor.clear
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model: MessageModel = messageList[indexPath.row]
        return model.messageHeight + 10.0 + 4.0
    }
    
}

